package com.woniuxy.kaer.service.consumer;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.woniuxy.kaer.service.service.ServiceOrderService;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class CheckPayConsumer {
    @Resource
    private ServiceOrderService serviceOrderService;
    @Resource
    private AlipayClient alipayClient;
    @RabbitHandler
    @RabbitListener(bindings ={
            @QueueBinding(
                    value=@Queue(value="check_pay_queue"),
                    exchange = @Exchange(value="d2",type="direct"),
                    key="check_pay"
            )
    })
    public void checkPay(String serviceOrderId) throws Exception{
//        System.out.println(orderNUm);
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ serviceOrderId+"\"}");
        String result = alipayClient.execute(alipayRequest).getBody();
        System.out.println(result);
        String orderInfo= JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode=JSONUtil.parseObj(orderInfo).get("code").toString();
        if("10000".equals(payCode)){
            String tradeStatus = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            if("TRADE_SUCCESS".equals(tradeStatus)){
                String payTime = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
                //用户已经完成支付
                serviceOrderService.updateOrder(serviceOrderId,payTime);
                return;
            }
        }
        //表示未支付成功
        serviceOrderService.cancelOrder(serviceOrderId);
    }
}
